package com.sh.personnel.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sh.personnel.config.redis.RedisConstant;
import com.sh.personnel.security.util.SecurityUtil;
import com.sh.personnel.service.UserInfoService;
import com.sh.personnel.util.EmailUtil;
import com.sh.personnel.util.RandomUtil;
import com.sh.personnel.util.result.Result;
import com.sh.personnel.vo.RegisterVo;
import com.sh.personnel.vo.dto.PasswordDto;
import com.sh.personnel.vo.dto.UserInfoDto;
import org.apache.ibatis.annotations.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * 个人用户信息
 * @author 林思浩
 * @date 2020/03/12 15:42
 */
@RestController
@RequestMapping("/user")
public class UserInfoController {

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    EmailUtil emailUtil;

    /**
     * 获取个人头像
     * @return
     */
    @GetMapping("/avatar")
    public Result getUserAvatar() {
        String avatar = userInfoService.getUserAvatar(SecurityUtil.getUser().getUserId());
        return Result.success().setData("avatar", avatar);
    }

    /**
     * 获取个人信息
     * @return
     */
    @GetMapping("/information")
    public Result getUserInformation() {
        UserInfoDto userInfo = userInfoService.getUserInfo(SecurityUtil.getUser().getUserId());
        return Result.success().setData("user_info", userInfo);
    }

    /**
     * 修改个人信息
     * @param userInfo
     * @return
     */
    @PutMapping("/information")
    public Result alterUserInformation(@RequestBody UserInfoDto userInfo){
        boolean bool = userInfoService.updateUserInfo(userInfo);
        return bool ? Result.success("更新成功") : Result.fail("更新失败");
    }

    /**
     * 上传个人头像
     * @param avatar
     * @return
     */
    @PutMapping("/avatar")
    public Result uploadAvatar(@RequestBody String avatar) {
        avatar = (String) JSON.parseObject(avatar).get("avatar");
        boolean bool = userInfoService.uploadAvatar(SecurityUtil.getUser().getUserId(), avatar);
        return bool ? Result.success() : Result.fail();
    }

    /**
     * 解除邮箱绑定
     * @return
     */
    @PostMapping("/email/unbind")
    public Result unbindEmail() {
        String userId = SecurityUtil.getUser().getUserId();
        String token = RandomUtil.generateUuid();
        redisTemplate.opsForValue().set(RedisConstant.TOKEN_EMAIL_BIND + token, userId, 5, TimeUnit.MINUTES);
    return Result.success().setData("bind_mail_token", token);
    }

    /**
     * 绑定邮箱
     * @param token
     * @param register
     * @return
     */
    @PostMapping("/email/bind")
    public Result bindEmail(@RequestParam("bind_token") String token,
                            @RequestBody RegisterVo register) {
        String email = register.getEmail();
        String userId = SecurityUtil.getUser().getUserId();
        if(userId.equals(redisTemplate.opsForValue().get(RedisConstant.TOKEN_EMAIL_BIND + token))) {
            if(userInfoService.updateEmail(SecurityUtil.getUser().getUserId(), email)) {
                redisTemplate.delete(RedisConstant.TOKEN_EMAIL_BIND + email);
                return Result.success();
            }
        }
        return Result.fail();
    }

    /**
     * 发送邮箱验证码
     * @param email
     * @return
     */
    @GetMapping("/email/code")
    public Result sendMailCode(String email) {
        if(EmailUtil.validMail(email)) {
            String code = RandomUtil.randomNumber(5);
            String text = "您的邮箱验证码为：" + code + "，请在两分钟内完成验证。";
            if(emailUtil.sendSimpleMail(email, "修改邮箱", text)) {
                redisTemplate.opsForValue().set(RedisConstant.EMAIL_CAPTCHA + email, code, 2, TimeUnit.MINUTES);
                return Result.success();
            }
        }
        return Result.fail();
    }

    /**
     * 修改密码
     * @param passwordDto
     * @return
     */
    @PutMapping("/pwd")
    public Result alterPassword(@RequestBody PasswordDto passwordDto) {
        if(userInfoService.checkPassword(passwordDto.getOldPassword())) {
            boolean bool = userInfoService.updatePassword(passwordDto);
            return bool ? Result.success("修改成功") : Result.fail("修改失败");
        }
        return Result.fail("旧密码输入错误");

    }
}
